package com.seraph.zys.web.system;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.seraph.bi.suite.support.security.BaseUser;
import com.seraph.bi.suite.support.security.LoginUtil;
import com.seraph.bi.suite.support.web.base.BaseResponse;
import com.seraph.bi.suite.support.web.json.JsonProviderController;
import com.seraph.zys.dao.ScOrgDAO;
import com.seraph.zys.dao.domain.ScOrg;
import com.seraph.zys.report.model.exp.ReportInitData;

@Controller
@RequestMapping("/initRepMataDataController.do")
public class InitRepMataDataController extends JsonProviderController {

	@Autowired
	private ReportInitData reportInitData;

	@Autowired
	private ScOrgDAO scOrgDAO;

	public void setScOrgDAO(ScOrgDAO scOrgDAO) {
		this.scOrgDAO = scOrgDAO;
	}

	public void setReportInitData(ReportInitData reportInitData) {
		this.reportInitData = reportInitData;
	}

	@Override
	protected Object handleJsonRequest(HttpServletRequest request,
			HttpServletResponse response) {
		BaseResponse baseResponse = null;
		String fiscalYear = request.getParameter("fiscalYear");
		String initDataStatusFlag = request.getParameter("initDataStatusFlag");

		BaseUser user = (BaseUser) LoginUtil.getUser();
		String orgCode = user.getOrgCode();
		if (fiscalYear != null && !"".equals(fiscalYear)) {
			int _fiscalYear = Integer.parseInt(fiscalYear);
			if ("checkStatus".equals(initDataStatusFlag)) {
				Map<String, String> checkInfo = new HashMap<String, String>();
				if (reportInitData.isInitialized(_fiscalYear, orgCode)) {
					checkInfo.put("initDataStatus", "1");
				} else {
					checkInfo.put("initDataStatus", "0");
				}
				return checkInfo;
			}
			String initDataStatus = request.getParameter("initDataStatus");
			boolean res = false;

			if ("0".equals(initDataStatus)) {
				res = reportInitData.initReportData(_fiscalYear, orgCode,
						getOrgLevel(orgCode), user.getUserName(), false);
			} else if ("1".equals(initDataStatus)) {
				res = reportInitData.initReportData(_fiscalYear, orgCode,
						getOrgLevel(orgCode), user.getUserName(), true);
			}
			if(res){
				baseResponse = new BaseResponse(BaseResponse.TRUE, "初始化成功！");
			}else{
				baseResponse = new BaseResponse(BaseResponse.FALSE, "初始化失败！");
			}
			
		} else {
			baseResponse = new BaseResponse(BaseResponse.FALSE, "初始年度不能为空！");
		}
		return baseResponse;
	}

	private int getOrgLevel(String orgCode) {
		ScOrg scOrg = scOrgDAO.selectByOrgCode(orgCode);
		return scOrg.getOrgLevel();

	}
}
